package com.summer.NIO;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class ServerSocketChannelCase1 {
	
	public static void main(String[] args) throws IOException, InterruptedException {
		boolean stop = true;
		
		ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
		serverSocketChannel.socket().bind(new InetSocketAddress(9999));
		
		serverSocketChannel.configureBlocking(false);
		
		
		while(true && stop){
			System.out.println("准备监听");
			SocketChannel socketChannel = serverSocketChannel.accept();
			System.out.println("收到消息");
			
			if(null == socketChannel){
				Thread.sleep(100);
				continue;
			}
			
			ByteBuffer readBuf = ByteBuffer.allocate(1024);
			readBuf.clear();
			int bytesRead = socketChannel.read(readBuf);
			readBuf.flip();
			byte[] body = new byte[readBuf.limit()];
			readBuf.get(body, 0, body.length);
			System.out.println("body:"+new String(body));
			
			
			String msg = "nihao";
			socketChannel.write(ByteBuffer.wrap(msg.getBytes()));
			socketChannel.close();
		}
		
		serverSocketChannel.close();
	}
	
}
